<template>
    <div style="height:100%;width:100%">
        <div id="relation" style="height:100%;width:100%"></div>
        <el-dialog :visible.sync="dialogVisible" width="600px">
            <div class="align-center">
                <div style="margin-bottom:15px">名称：<el-input v-arouse v-model="name" placeholder="请输入名称" style="width:400px"></el-input>
                </div>
                <div v-if="isAdd || relation">关系：<el-input v-arouse v-model="relation" placeholder="请输入关系" style="width:400px"></el-input>
                </div>
            </div>
            <div slot="footer">
                <div class="flex-center">
                    <el-button type="primary" @click="changeNode">q确 定</el-button>
                    <el-button @click="clear">取 消</el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script>
let addNode = () => { }
let deleteNode = () => { }
const { remote } = require('electron')
const { Menu, MenuItem } = remote
const addMenu = new Menu()
addMenu.append(new MenuItem({ label: '添加节点', click () { addNode() } }))
const deleteMenu = new Menu()
deleteMenu.append(new MenuItem({ label: '删除节点', click () { deleteNode() } }))
const echarts = require('echarts');
var size = 90; //节点大小
const dataColor = ['#48AFFF', '#4ECB73', '#FBD437', '#FF9F03', '#F56C6C', '#F841A0', '#CE3FF7', '#833EF6', '#48AFFF',
    '#4ECB73', '#FBD437', '#FF9F03', '#F56C6C', '#F841A0', '#CE3FF7', '#833EF6']
export default {
    props: {
        orignData: {
            type: Array,
            default: [
                {
                    "id": 1,
                    "contactName": "节点一",
                    "relation": "关系一"
                },
                {
                    "id": 2,
                    "contactName": "节点二",
                    "relation": "关系二"
                },
                {
                    id: 3,
                    "focusName": "根节点"
                }
            ]
        }
    },
    data () {
        return {
            isAdd: false,
            cacheOrignData: JSON.parse(JSON.stringify(this.orignData)),
            name: '',
            relation: '',
            dialogVisible: false,
            option: {
                color: ['#48AFFF', '#4ECB73', '#FBD437', '#FF9F03', '#F56C6C', '#F841A0', '#CE3FF7', '#833EF6', '#48AFFF',
                    '#4ECB73', '#FBD437', '#FF9F03', '#F56C6C', '#F841A0', '#CE3FF7', '#833EF6'],
                animationDurationUpdate: 1500,
                animationEasingUpdate: 'quinticInOut',
                label: {
                    normal: {
                        show: true,
                        textStyle: {
                            fontSize: 12
                        },
                    }
                },
                tooltip: {
                    formatter ({ name }) {
                        return name
                    }
                },
                legend: {
                    right: 50,
                    top: 50,
                    show: true,
                    data: [],
                    textStyle: {

                    }
                },
                series: [
                    {
                        type: 'graph',
                        layout: 'force',
                        focusNodeAdjacency: false,
                        roam: true,
                        categories: [],
                        zoom: window.innerWidth > 1440 ? 1 : 0.7,
                        // left:'center',
                        // top:'center',
                        // bottom:'center',
                        // right:'center',
                        // width: '25%',
                        // height: '25%',
                        symbolSize:(val,param)=>{
                            const {name} = param
                            const size = 9 -  Math.ceil(name.length / 20) ||1
                            return (name.length * size < 70) ? 70 : name.length * size
                        },
                        label: {
                            normal: {
                                width:150,
                                height:150,
                                show: true,
                                aligin: 'center',
                                textStyle: {
                                    fontSize: 18
                                },
                                formatter ({ name }) {
                                    // if (name.length <= 4) return name
                                    // if (name.length > 10) name = name.substr(0, 10)
                                    // if (name.length < 10 && name.length > 4) {
                                    //     let start = Math.ceil((10 - name.length) / 2)
                                    //     name = name.padStart(name.length + start, ' ')
                                    //     name = name.padEnd(10, ' ')
                                    // }
                                    const splitArr = Array(Math.ceil(name.length/4)).fill(4)
                                    let newName = []
                                    name = name.split('')
                                    splitArr.forEach(item => {
                                        newName.push(name.splice(0, item))
                                    })
                                    // console.log(newName.join(`\n`).replace(/\,/g, ''))
                                    // console.log(newName.join(`\n`).replace(/\,/g, '').length)
                                    return newName.join(`\n`).replace(/\,/g, '')
                                }
                            }
                        },
                        force: {
                            "gravity": 0.1,
                            // initLayout: 'circular',
                            "friction": 0.6,
                            repulsion: 1200,
                            edgeLength: 200
                        },
                        edgeLabel: {
                            normal: {
                                show: true,
                                textStyle: {
                                    fontSize: 17
                                },
                                formatter: "{c}"
                            }
                        },
                        data: [],
                        links: [],
                        lineStyle: {
                            normal: {
                                opacity: 0.9,
                                width: 2,
                                curveness: 0
                            }
                        },
                        tooltip: {

                        }
                    }
                ]
            }
        }
    },
    // watch: {
    //     orignData: {
    //         immediate: true,
    //         handler (nval) {
    //             console.log(nval)
    //             let seriesList = [], seriesData = [], categories = new Map(), linksData = [], legendData = new Set()
    //             let focusName = nval[nval.length - 1].focusName
    //             nval.forEach((item, index) => {
    //                 if (item.relation) {
    //                     categories.set(item.relation, dataColor[categories.size])
    //                     legendData.add(item.relation)
    //                 }
    //                 seriesData.push({
    //                     // x: index * 50,
    //                     // y: size + index * 10,
    //                     name: item.contactName || item.focusName,
    //                     category: item.relation,
    //                     symbolSize: size,
    //                     // draggable: true,
    //                     "label": {
    //                         // position: "bottom",
    //                         color: "#fff"
    //                     },
    //                     itemStyle: { color: categories.get(item.relation) || '#0ff' }
    //                 })
    //                 linksData.push({
    //                     source: focusName,
    //                     target: item.contactName,
    //                     value: item.relation
    //                 })

    //             })
    //             let newArry = []
    //             Array.from(categories.keys()).forEach(item => {
    //                 newArry.push({ name: item })
    //             })
    //             this.option.legend.legendData = Array.from(legendData)
    //             this.option.series[0].categories = newArry
    //             this.option.series[0].data = seriesData
    //             this.option.series[0].links = linksData
    //             this.$nextTick(() => {
    //                 this.drawRelation()
    //             })
    //         }

    //     }
    // },
    mounted () {
        this.$nextTick(() => {
            this.updateChart(this.orignData)
        })
    },
    methods: {
        updateChart (nval) {
            console.log(nval)
            let seriesList = [], seriesData = [], categories = new Map(), linksData = [], legendData = new Set()
            let focusName = nval[nval.length - 1].focusName
            nval.forEach((item, index) => {
                if (item.relation) {
                    categories.set(item.relation, dataColor[categories.size])
                    legendData.add(item.relation)
                }
                seriesData.push({
                    // x: index * 50,
                    // y: size + index * 10,
                    name: item.contactName || item.focusName,
                    category: item.relation,
                    // symbolSize: ,
                    // draggable: true,
                    "label": {
                        // position: "bottom",
                        color: "#fff"
                    },
                    itemStyle: { color: categories.get(item.relation) ?'#67C23A' : '#48AFFF' }
                })
                linksData.push({
                    source: focusName,
                    target: item.contactName,
                    value: item.relation
                })

            })
            let newArry = []
            Array.from(categories.keys()).forEach(item => {
                newArry.push({ name: item })
            })
            this.option.legend.legendData = Array.from(legendData)
            this.option.series[0].categories = newArry
            this.option.series[0].data = seriesData
            this.option.series[0].links = linksData
            this.$nextTick(() => {
                this.drawRelation()
            })
        },
        drawRelation () {
            console.log('drawRelation')
            let mychart = null
            mychart = echarts.init(document.getElementById('relation'))
            mychart.setOption(this.option)
            // mychart.on('dblclick', { dataType: 'node' }, (params) => {
            //     const { data } = params
            //     this.dialogVisible = true
            //     this._cacheName = this.name = data.name
            //     this._relation = this.relation = data.category || ''
            //     this._index = params.dataIndex
            // })
            // mychart.on('contextmenu', { dataType: 'node' }, (params) => {
            //     if (params.dataIndex === this.cacheOrignData.length - 1) {
            //         addMenu.popup()
            //         addNode = () => {
            //             this.isAdd = true
            //             this.dialogVisible = true
            //         }
            //     } else {
            //         deleteMenu.popup()
            //         deleteNode = () => {
            //             this.$emit('deleteNode',params.dataIndex)
            //         }
            //     }
            // })
        },
        changeNode () {
            if (this.isAdd) {
                let param = {
                    name: this.name,
                    ra: this.relation
                }
                let pop = this.cacheOrignData.pop()
                this.$emit('addNode',this.cacheOrignData.length,param)
                this.isAdd = false
            } else {
                if (this.name === this._cacheName && this._relation === this.relation) {
                    this.dialogVisible = false
                    return
                }
                if (this._index >= 0 && this._index < this.cacheOrignData.length) {
                    if (this._index === this.cacheOrignData.length - 1) {
                        let obj =
                            this.cacheOrignData[this._index].focusName = this.name
                    } else {
                        this.cacheOrignData[this._index].contactName = this.name
                        this.cacheOrignData[this._index].relation = this.relation
                    }
                }
                this._cacheName = ''
                this._relation = ''
            }
            this.name = ''
            this.relation = ''
            this.$emit('changeOrignData', JSON.parse(JSON.stringify(this.cacheOrignData)))
            this.dialogVisible = false
        },
        clear () {
            this.name = ''
            this.relation = ''
            this.dialogVisible = false
        }
    }
}
</script>

<style>
</style>